﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using CLFramework.Data;
using CLFramework;

namespace CLFramework.Data
{
    public abstract class DataProviderBase
    {
        protected abstract SqlConnection GetSqlConnection();

        public virtual SqlConnection CreateSqlConnection()
        {
            return GetSqlConnection();
        }

        public List<T> GetAllFromTable<T>(string tableName)
            where T : ILoadDr
        {
            List<T> result = new List<T>();

            using (SqlConnection conn = GetSqlConnection())
            {
                using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, string.Format("select * from {0} with(nolock)", tableName), System.Data.CommandType.Text, null))
                {
                    while (dr.Read())
                    {
                        T model = (T)EmitHelper.GetInstanceCreator(typeof(T)).Invoke();
                        model.LoadData(dr);
                        result.Add(model);
                    }
                }
            }

            return result;
        }

        public List<T> GetAllFromQuery<T>(string query)
            where T : ILoadDr
        {
            List<T> result = new List<T>();

            using (SqlConnection conn = GetSqlConnection())
            {
                using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, query, System.Data.CommandType.Text, null))
                {
                    while (dr.Read())
                    {
                        T model = (T)EmitHelper.GetInstanceCreator(typeof(T)).Invoke();
                        model.LoadData(dr);
                        result.Add(model);
                    }
                }
            }

            return result;
        }

        public T GetIDBySP<T>(string spName, params object[] parameters)
        {
            var ids = GetIDsBySP<T>(spName, parameters);
            if (ids != null && ids.Count > 0)
            {
                return ids[0];
            }
            else
            {
                return default(T);
            }
        }

        public List<T> GetIDsBySP<T>(string spName, params object[] parameters)
        {
            List<T> result = new List<T>();

            using (SqlConnection conn = GetSqlConnection())
            {
                using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, spName
                    , parameters))
                {
                    result = SqlHelper.PopulateReadersToIds<T>(dr);
                }
            }
            return result;
        }


    }
}
